import 'package:acgn_pioneer/providers/pop_slide_provider.dart';
import 'package:flutter/material.dart';

import '../public.dart';

// 滑动弹窗
class SlideDialogComponent extends StatefulWidget {
  final Widget child;

  SlideDialogComponent({@required this.child});

  @override
  _SlideDialogComponentState createState() => _SlideDialogComponentState();
}

class _SlideDialogComponentState extends State<SlideDialogComponent> {
  var _initialPosition = 0.0;
  var _currentPosition = 0.0;
  var canScroll = false; // 是否响应slide事件
  PopSlideProvider popSlideProvider;
  var deviceWidth = ScreenUtil.getInstance().screenWidth;
  var deviceHeight = ScreenUtil.getInstance().screenHeight;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    popSlideProvider = Provider.of<PopSlideProvider>(context);
    return SingleChildScrollView(
      padding: MediaQuery.of(context).viewInsets +
          EdgeInsets.only(top: _currentPosition),
      child: MediaQuery.removeViewInsets(
        removeLeft: true,
        removeTop: true,
        removeRight: true,
        removeBottom: true,
        context: context,
        child: Listener(
            onPointerDown: _onDragStart,
            onPointerMove: _onDragUpdate,
            onPointerUp: _onDragEnd,
            child: Center(
              child: Container(
                width: deviceWidth,
                height: deviceHeight,
                child: widget.child,
              ),
            )),
      ),
    );
  }

  void _onDragStart(PointerDownEvent drag) {
    if (!mounted) {
      return;
    }
    setState(() {
      _initialPosition = drag.position.dy;
    });
  }

  void _onDragUpdate(PointerMoveEvent drag) {
    if (!mounted || !popSlideProvider.isCanSlide) {
      return;
    }
    setState(() {
      final temp = _currentPosition;
      _currentPosition = drag.position.dy - _initialPosition;
      if (_currentPosition < 0) {
        _currentPosition = temp;
      }
    });
  }

  void _onDragEnd(PointerUpEvent drag) {
    if (_currentPosition > 100.0) {
      Navigator.pop(context);
      return;
    }
    if (!mounted) {
      return;
    }
    setState(() {
      _currentPosition = 0.0;
    });
  }
}
